<script setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoleApi } from '@/api/role/index'
import { useMenuApi } from '@/api/menu'

// 状态管理
const roleFormRef = ref()
const roleApi = useRoleApi()
const menuApi = useMenuApi()

const menuTreeRef = ref()
const state = reactive({
  loading: false,
  pageIndex: 1,
  pageSize: 6,
  page: {
    records: [],
    total: 0
  },
  searchParams: {
    name: '',
    code: '',
    status: undefined
  },
  selectionIds: [],

  showEdit: false,
  dialogTitle: '',
  roleForm: {
    id: undefined,
    name: '',
    code: '',
    status: 0,
    description: ''
  },
  roleRules: {
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入角色编码', trigger: 'blur' }]
  },

  authVisible: false,
  authTitle: '',
  authData: [],
  authRoleId: undefined,
  menuExpand: false,
  menuChecked: false,
  menuStrictlyCheck: true
})

// 获取表格数据
const getTableData = async (current = 1) => {
  try {
    state.loading = true
    state.pageIndex = current
    const params = { pageIndex: state.pageIndex, pageSize: state.pageSize }
    state.page = await roleApi.getPage(params, state.searchParams)
  } finally {
    state.loading = false
  }
}

// 重置查询
const resetSearch = () => {
  state.searchParams = {}
  getTableData()
}

// 处理每页大小改变
const handleSizeChange = async (val) => {
  state.pageSize = val
  await getTableData()
}

// 处理复选框选中
const handleSelectionChange = (rows) => {
  state.selectionIds = rows.map((v) => v.id)
}

// 打开编辑弹窗
const openEdit = (row) => {
  state.showEdit = true
  state.dialogTitle = '添加角色'
  if (row) {
    state.dialogTitle = '修改角色'
    state.roleForm = { ...row }
  }
}

// 处理编辑弹窗关闭
const handleClose = () => {
  roleFormRef.value.resetFields()
}

// 处理提交
const handleSubmit = async () => {
  roleFormRef.value.validate(async (valid) => {
    if (valid) {
      if (state.roleForm.id) {
        await roleApi.update(state.roleForm)
      } else {
        await roleApi.save(state.roleForm)
      }
      state.showEdit = false
      ElMessage.success('操作成功')
      await getTableData()
    }
  })
}

// 打开授权弹窗
const openAuth = async (row) => {
  state.authVisible = true
  state.authRoleId = row.id
  state.authTitle = `${row.name} 授权`

  state.authData = await menuApi.getList({})

  const res = await roleApi.getAuth(row.id)

  menuTreeRef.value.setCheckedKeys([])

  res.forEach((i) => {
    if (!i) {
      return
    }

    const node = menuTreeRef.value.getNode(i)
    if (node.isLeaf) {
      menuTreeRef.value.setChecked(node, true)
    }
  })
}

// 展开菜单树
const expandTreeHandle = (val) => {
  const nodes = menuTreeRef.value.store.nodesMap
  for (const i in nodes) {
    nodes[i].expanded = val
  }
}

// 菜单树全选
const checkedTreeHandle = (val) => {
  menuTreeRef.value.setCheckedNodes(val ? state.authData : [])
}

// 菜单树联选
const strictlyHandler = (val) => {
  state.menuStrictlyCheck = val
}

// 保存权限
const saveAuth = async () => {
  // 选中的节点
  const checkedKeys = menuTreeRef.value.getCheckedKeys()
  // 半选的节点
  const halfCheckedKeys = menuTreeRef.value.getHalfCheckedKeys()

  await roleApi.saveAuth({
    roleId: state.authRoleId,
    menuIds: [...checkedKeys, ...halfCheckedKeys]
  })

  state.authVisible = false
  ElMessage.success('保存成功')
  window.location.reload()
}

// 处理删除
const handleRemove = (ids) => {
  ElMessageBox.confirm('确认要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await roleApi.remove(ids)
    ElMessage.success('删除成功')
    await getTableData()
  })
}

// 初始化加载角色
onMounted(() => {
  getTableData()
})
</script>

<template>
  <el-card>
    <el-form :model="state.searchParams" :inline="true">
      <el-row>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="state.searchParams.name" placeholder="请输入角色名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="角色编码" prop="code">
            <el-input v-model="state.searchParams.code" placeholder="请输入角色编码" clearable />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="角色状态" prop="status">
            <el-select v-model="state.searchParams.status" clearable placeholder="请选择角色状态" style="width: 190px">
              <el-option :value="0" label="启用" />
              <el-option :value="1" label="禁用" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item>
            <el-button type="primary" icon="search" @click="getTableData()"> 搜索 </el-button>
            <el-button icon="refresh" @click="resetSearch"> 清空 </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row>
      <el-button v-auth="'role:save'" type="primary" icon="plus" @click="openEdit(null)">创建角色</el-button>
      <el-button
        v-auth="'role:delete'"
        type="danger"
        icon="delete"
        @click="handleRemove(state.selectionIds)"
        :disabled="state.selectionIds.length < 1"
        >批量删除</el-button
      >
    </el-row>

    <el-table
      class="mt10"
      :loading="state.loading"
      element-loading-text="正在努力加载数据中..."
      :data="state.page.records"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" fixed="left" width="55" />
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="name" label="角色名称" min-width="120" show-overflow-tooltip />
      <el-table-column prop="code" label="角色编码" min-width="120" sortable show-overflow-tooltip />
      <el-table-column prop="status" label="状态" min-width="100">
        <template #default="{ row }">
          <el-tag type="success" v-if="row.status === 0" effect="plain">正常</el-tag>
          <el-tag type="danger" v-if="row.status === 1" effect="plain">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" min-width="120" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" min-width="120" sortable show-overflow-tooltip />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-link v-auth="'role:save-auth'" type="primary" icon="CircleCheck" @click="openAuth(row)">授权 </el-link>
          <el-divider v-auth="'role:update'" direction="vertical" />
          <el-link v-auth="'role:update'" type="success" icon="edit" @click="openEdit(row)">编辑 </el-link>
          <el-divider v-auth="'role:delete'" direction="vertical" />
          <el-link type="danger" v-auth="'role:delete'" icon="remove" @click="handleRemove([row.id])">删除 </el-link>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="mt10"
      :current-page="state.page.current"
      :page-size="state.page.size"
      :total="state.page.total"
      :page-sizes="[1, 3, 6, 9, 12, 15, 18]"
      layout="total, sizes, ->, prev, pager, next, jumper"
      background
      @current-change="getTableData"
      @size-change="handleSizeChange"
    />

    <el-dialog v-model="state.showEdit" :title="state.dialogTitle" @close="handleClose">
      <el-form ref="roleFormRef" :model="state.roleForm" :rules="state.roleRules" label-width="100px">
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="state.roleForm.name" placeholder="请输入角色名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="角色编码" prop="code">
              <el-input v-model="state.roleForm.code" placeholder="请输入角色编码" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="角色状态" prop="status">
              <el-radio-group v-model="state.roleForm.status">
                <el-radio border :value="0">启用</el-radio>
                <el-radio border :value="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="角色描述" prop="description">
              <el-input type="textarea" v-model="state.roleForm.description" placeholder="请输入描述" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="state.showEdit = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog :title="state.authTitle" v-model="state.authVisible">
      <div>
        <el-checkbox v-model="state.menuExpand" label="展开/折叠" @change="expandTreeHandle($event)" />
        <el-checkbox v-model="state.menuChecked" label="全选/全不选" @change="checkedTreeHandle($event)" />
        <el-checkbox v-model="state.menuStrictlyCheck" label="联选" @change="strictlyHandler($event)" />
      </div>
      <el-tree
        ref="menuTreeRef"
        style="max-height: calc(60vh - 140px); overflow: auto"
        :data="state.authData"
        show-checkbox
        :check-strictly="!state.menuStrictlyCheck"
        node-key="id"
        :props="{ children: 'children', label: 'name' }"
      />
      <template #footer>
        <el-button @click="state.authVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAuth()">确 定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>
